import os
import winreg


def read_env():
    path  =  get_user_path()
    env_vars = get_user_env_var()
    return path, env_vars


def get_user_env_var():
    env_vars = {}
    try:
        with winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            "Environment",
            0,  # 默认权限
            winreg.KEY_READ,
        ) as key:
            i = 0
            while True:
                try:
                    name, value, _ = winreg.EnumValue(key, i)
                    if name.upper() == "PATH":
                        i += 1
                        continue
                    env_vars[name] = value
                    i += 1
                except OSError:
                    break
        return env_vars
    except Exception as e:
        print(f"Error reading registry: {e}")
        return None

def reset_path(paths : list  ):
    new_path = os.pathsep.join(paths)
    user_path = get_user_path()
    if user_path == new_path:
        print("PATH is already set to the desired value")
        return
    set_user_env_var("PATH", new_path)
    print(f"New PATH: {new_path}")


def set_user_env_var(name, value):
    try:
        key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            "Environment",
            0,  # 默认权限
            winreg.KEY_SET_VALUE,
        )
        winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value)
        winreg.CloseKey(key)

        return True
    except Exception as e:
        print(f"Error: {e}")
        return False


def delete_user_env_var(name):

    try:
        key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            "Environment",
            0,  # 默认权限
            winreg.KEY_SET_VALUE,
        )

        winreg.DeleteValue(key, name)
        winreg.CloseKey(key)


        return True
    except FileNotFoundError:
        print(f"变量 {name} 不存在，无需删除")
        return False
    except Exception as e:
        print(f"删除失败: {e}")
        return False

def get_user_path():
    try:
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment") as key:
            path, _ = winreg.QueryValueEx(key, "PATH")
            return path
    except WindowsError:
        return None


def main():
    path,  env_vars  = read_env()
    paths  =check_path(path)
    reset_path(paths)
    check_env(env_vars)


def check_path(path: str ):
    paths = path.split(os.pathsep)

    paths =  list(filter( lambda x: x != '', paths))
    # print("original path:", paths)
    new_paths= []
    for path in paths:
        if not os.path.exists(path)  :
            print(f"Path {path} does not exist")
            continue
        new_paths.append(path)
    return new_paths


def check_env(env_vars : dict  ):
    new_env_vars = {}
    for key  in env_vars.keys():
        value = env_vars[key]
        if  os.path.exists(value) :
            # print(f"{key} is set to {value}")
            continue
        else :
            print(f"{key} is not set to a valid path {value}")
            new_env_vars[key] = value
    old_env_vars = get_user_env_var()
    if new_env_vars == old_env_vars:
        print("Environment variables are already set to the desired value")
        return
    for key  in new_env_vars.keys():
        delete_user_env_var(key)



if __name__ == "__main__":
    main()
